#include "ProfileRadioMenuButton.h"
#include "NetcfgCppFunctions.h"
#include <iostream>
#include "config.h"

#ifdef HAVE_LIBNOTIFY
#include <libnotify/notify.h>
#endif

#include <pthread.h>
#include <string>

static pthread_mutex_t* connectionLock;

static char* connectMsg(const char* profile);
/*
 * A menu item with a radio button that is on when the profile it represents is 
 * connected. Click events should be bound to the connect function that connects
 * to the profile that's named according to the label argument.
 */ 

ProfileRadioMenuButton::ProfileRadioMenuButton(Gtk::RadioMenuItem::Group& groupx, 
		const Glib::ustring& label, pthread_mutex_t&  m) : RadioMenuItem(groupx, label) {
	connectionLock = &m;
	set_use_underline(false); // So profiles with underscore won't be messed up.
}

void ProfileRadioMenuButton::connect() {
	if(get_active()) {
		pthread_t con;

		
		size_t nameLen = strlen(get_label().c_str());
		char* profileName = (char*) malloc(nameLen + 1);
		memcpy(profileName,get_label().c_str(), nameLen + 1); 
		pthread_create(&con, NULL, 
				ProfileRadioMenuButton::connectionThread, 
				(void*) profileName);	
	}
}

void* ProfileRadioMenuButton::connectionThread(void *profile) {
	std::cout<<"Heya\n";
	if(pthread_mutex_trylock(connectionLock) == 0) return 0;

	std::cout<<"Starting connection\n";
	
	if (!NetcfgCpp::connect(std::string( (char *) profile))) { 
		#ifdef HAVE_LIBNOTIFY
		NotifyNotification * Failed =
		       	notify_notification_new("Netcfg", "Connection failed", NULL);
		notify_notification_show(Failed, NULL);
		#endif	
	}
	free(profile);
	pthread_mutex_unlock(connectionLock);
	return 0;
}

char* connectMsg(const char* profile) {
	size_t lenProf = strlen(profile);
	char msg[] = "Connecting to profile ";
	size_t lenMsg = strlen(msg);

	char* formattedMsg = (char*)malloc(lenProf + lenMsg + 2);
	memcpy(formattedMsg, msg, lenMsg);
	memcpy(formattedMsg + lenMsg, profile, lenProf + 1);

	return formattedMsg;
}
